import { Request, Response, NextFunction } from 'express'
import HttpException from '../models/httpException';
import httpCodes from "http-status-codes";
import { validateRegisterInput } from '../utils/validator';
import { IUserDocument, User } from '../models';
import { UserPayload } from 'src/typings/jwt';
import jwt from 'jsonwebtoken';
import configs from '../config'


export const register = async (req: Request, res: Response, next: NextFunction) => {
    try {
        let { username, password, confirmPassword, email, address } = req.body;
        const { valid, errors } = validateRegisterInput(username, password, confirmPassword, email);
        if (!valid) {
            throw new HttpException(httpCodes.UNPROCESSABLE_ENTITY, errors);
        }
        let user: IUserDocument = new User({
            username,
            password,
            email,
            address,
        });
        let oldUser: IUserDocument | null = await User.findOne({
            username: user.username
        });
        if (oldUser) {
            throw new HttpException(httpCodes.UNPROCESSABLE_ENTITY, "用户名重复");
        }
        await user.save();
        let token = user.generateToken();
        res.json({
            success: true,
            data: { token }
        });
    } catch (error) {
        next(error);
    }
}

export const login = async function (req: Request, res: Response, next: NextFunction) {
    try {
        let { username, password } = req.body;
        let user = await User.login(username, password);
        if (user) {
            let token = user.generateToken();
            res.json({
                success: true,
                data: {
                    token
                }
            })
        } else {
            throw new HttpException(httpCodes.UNAUTHORIZED, "登录失败");
        }
    } catch (error) {
        next(error);
    }
}

const getUser = async (req: Request)=>{
    const authorization = req.headers["authorization"];
    if (authorization) {
        const token = authorization.split(" ")[1];
        if (token) {
            try {
                const payload: UserPayload = jwt.verify(token, configs.JWT_SECRET_KEY) as UserPayload;
                const user = await User.findById(payload.id);
                if (user) {
                    delete user.password;
                    return { success: true, user }
                } else {
                    return { success: false, error: new HttpException(httpCodes.UNAUTHORIZED, "用户名不合法!") }
                }
            } catch (e) {
                return { success: false, error: new HttpException(httpCodes.UNAUTHORIZED, "【token】不合法!") }
            }
        }
        else {
            return { success: false, error: new HttpException(httpCodes.UNAUTHORIZED, "【token】未提供") }
        }
    }
    else {
        return { success: false, error: new HttpException(httpCodes.UNAUTHORIZED, "未提供【authorization】请求头") }
    }
}

export const validate = async (req: Request, res: Response, next: NextFunction) => {
    let {success,error,user}= await getUser(req);
    if(!success){
        next(error);
        return;
    }
    res.json({
        success,
        user
    })
}

export const uploadAvatar = async (req: Request, res: Response, next: NextFunction) => {
    let {success,error,user}= await getUser(req);
    if(!success){
        next(error);
        return;
    }
    let domain = process.env.DOMAIN || `${req.protocol}://${req.headers.host}`;
    // let avatar = `${domain}/uploads/${req.file.filename}`;
    // 放到前端目录-后端目录还要设置代理相对麻烦
    let avatar = `/images/uploads/${req.file.filename}`;
    await User.updateOne({ _id: (user as IUserDocument).id}, { avatar });
    res.send({ success: true, data: avatar });
}